//
//  AXFMineViewController.m
//  aixinfeng005
//
//  Created by zhanghaifeng on 16/10/10.
//  Copyright © 2016年 BBSWaitting. All rights reserved.
//

#import "AXFMineViewController.h"
#import "UIColor+Addition.h"
//#import "TTTAttributedLabel.h"
#import <UIImageView+WebCache.h>
#import "AXFMineSubViewController.h"

@interface AXFMineViewController ()
//<TTTAttributedLabelDelegate, UIActionSheetDelegate>

@end

@implementation AXFMineViewController
{
    NSTimer *timer;   //定时器
    NSInteger leftSconds;  //秒数
    UIButton *_sendButton;
    UILabel *_label;
    UITextField *_text1;
    UITextField *_text2;
    UIView *_vc1;
    UIView *_vc2;
    UIButton *_certainBtn;
//    TTTAttributedLabel *_helpLabel;
    
}
static inline NSRegularExpression * NameRegularExpression() {
    static NSRegularExpression *_nameRegularExpression = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _nameRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"^\\w+" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    
    return _nameRegularExpression;
}
#warning 登录成功跳转界面接口,come here~
- (void)certainAction:(UIButton *)sender{
    NSLog(@"登录成功跳转界面接口,come here~");
    AXFMineSubViewController * mineSubVC = [AXFMineSubViewController new];

    [self.navigationController pushViewController:mineSubVC animated:YES];
    
    
}
//点击Button 触发的方法
-(void)sendAction:(UIButton *)sender
{
    
    BOOL isMobileNumber = [self isMobileNumber:_text1.text];
    if (isMobileNumber) {
        [sender removeFromSuperview];
        
        [self.view addSubview:_label];
        timer.fireDate = [NSDate distantPast];
        
        [_label mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_text1);
            make.right.equalTo(self.view).offset(-8);
            make.width.offset(100);
            make.height.offset(28);
        }];
    }else{
        UIAlertController *av = [UIAlertController alertControllerWithTitle:@"请输入正确的号码" message:@"重新输入" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *ac = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [av addAction:ac];
    
        [self presentViewController:av animated:YES completion:nil];
    }
    
}

//定时器 实现的方法
-(void)tickDown{
 
    leftSconds -=1;
    
    if (leftSconds>0) {
        _label.text = [NSString stringWithFormat:@"%ld秒后重试",leftSconds];
    }
    
    if (leftSconds == 0) {
        [timer invalidate];
        timer.fireDate = [NSDate distantFuture];
        [_label removeFromSuperview];
        [self.view addSubview:_sendButton];
        [self viewDidLoad];
    }
    
}

///// 手机号码的有效性判断
//检测是否是手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//TTTAttributedLabel代理方法
//- (void)attributedLabel:(__unused TTTAttributedLabel *)label
//   didSelectLinkWithURL:(NSURL *)url
//{
//    
//    [[[UIActionSheet alloc] initWithTitle:[url absoluteString] delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Open Link in Safari", nil), nil] showInView:self.view];
//}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:actionSheet.title]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"验证手机";
    [self setupUI];
}

- (void)setupUI{
    //图片
    UIImageView *imgV = [[UIImageView alloc] init];
    imgV.backgroundColor = [UIColor orangeColor];
    NSURL *URL = [NSURL URLWithString:@"http://www.chinairn.com/UserFiles/image/20160325/20160325093424_3785.jpg"];
    [imgV sd_setImageWithURL:URL];
    [self.view addSubview:imgV];
    //账号
    _text1 = [[UITextField alloc] init];
    _text1.placeholder = @"请输入您的手机号";
    _text1.font = [UIFont systemFontOfSize:12];
    
    [self.view addSubview:_text1];
    //黄线
    UIView *vc1 = [[UIView alloc] init];
    vc1.backgroundColor = [UIColor colorWithHex:0xF1F1F1];
    
    [self.view addSubview:vc1];
    //短信
    leftSconds = 60;
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tickDown) userInfo:nil repeats:YES];
    timer.fireDate = [NSDate distantFuture];
    
    _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sendButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _sendButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [_sendButton setBackgroundColor:[UIColor colorWithHex:0xff9600]];
    _sendButton.layer.cornerRadius = 5;
    _sendButton.layer.masksToBounds = YES;

    _sendButton.selected = NO;
    
    [_sendButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sendButton];

    
    //等待短信时间
    _label = [[UILabel alloc] init];
    _label.backgroundColor = [UIColor lightGrayColor];

    _label.font = [UIFont systemFontOfSize:14.0];
    _label.layer.cornerRadius = 5;
    _label.layer.masksToBounds = YES;
    _label.textAlignment = NSTextAlignmentCenter;

    [self.view addSubview:_label];
    
    
    //密码
    UITextField *text2 = [[UITextField alloc] init];
    text2.placeholder = @"请输入短信验证码";
    text2.font = [UIFont systemFontOfSize:12];
    //254 212 48
    [self.view addSubview:text2];
    //黄线
    UIView *vc2 = [[UIView alloc] init];
    vc2.backgroundColor = [UIColor colorWithHex:0xF1F1F1];
    
    [self.view addSubview:vc2];
    //确定
    UIButton *certainBtn = [[UIButton alloc] init];
    [certainBtn setTitle:@"确定" forState:UIControlStateNormal];
    [certainBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    certainBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [certainBtn setBackgroundColor:[UIColor colorWithHex:0xff9600]];
    certainBtn.layer.cornerRadius = 5;
    certainBtn.layer.masksToBounds = YES;
    [certainBtn addTarget:self action:@selector(certainAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:certainBtn];
    
//    TTTAttributedLabel *helpLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(100, 120, 120, 60)];
//    helpLabel.font = [UIFont systemFontOfSize:14];
//    helpLabel.textColor = [UIColor blackColor];
//    helpLabel.lineBreakMode = NSLineBreakByCharWrapping;
//    helpLabel.numberOfLines = 0;
//    
//    //检测url
//    helpLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
//    
//    //对齐方式
//    helpLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
//    
//    //行间距
//    helpLabel.lineSpacing = 8;
//    
//    helpLabel.delegate = self; // Delegate
//    //NO 不显示下划线
//    helpLabel.linkAttributes = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
    
    NSString *text = @"收不到短信? 请查百度 ";
    
//    
//    [helpLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString)
//     {
//         
//         //设置可点击文字的范围
//         NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"请查百度" options:NSCaseInsensitiveSearch];
//         
//         //设定可点击文字的的大小
//         UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:14];
//         CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
//         
//         if (font) {
//             
//             //设置可点击文本的大小
//             [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];
//             
//             //设置可点击文本的颜色
//             [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor blueColor] CGColor] range:boldRange];
//             
//             CFRelease(font);
//             
//         }
//         return mutableAttributedString;
//     }];
    
    //正则
    NSRegularExpression *regexp = NameRegularExpression();
    
    NSRange linkRange = [regexp rangeOfFirstMatchInString:text options:0 range:NSMakeRange(7, 4)];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.baidu.com/"]];
    
    //设置链接的url
//    [helpLabel addLinkToURL:url withRange:linkRange];
//    
//    
//    [self.view addSubview:helpLabel];



#pragma make - 约束
    //图片
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.equalTo(self.view).offset(0);
        CGFloat imgH = self.view.bounds.size.width * 424 / 600;
        make.height.offset(imgH);
    }];
    //账号
    [_text1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imgV.mas_bottom).offset(12);
        make.left.equalTo(self.view).offset(8);
        make.right.equalTo(_sendButton.mas_left).offset(0);

    }];
    //获取短信
    [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_text1);
        make.right.equalTo(self.view).offset(-8);
        make.width.offset(100);
    }];
    
    //黄线
    [vc1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_text1.mas_bottom).offset(12);
         make.left.right.equalTo(self.view).offset(0);
        make.height.offset(1);
        
    }];
    //密码
    [text2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vc1.mas_bottom).offset(12);
        make.left.equalTo(self.view).offset(8);
        make.right.equalTo(self.view).offset(0);
    }];
    //黄线
    [vc2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(text2.mas_bottom).offset(12);
        make.left.right.equalTo(self.view).offset(0);
        make.height.offset(1);
    }];

    //确定
    [certainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vc2.mas_bottom).offset(20);
       make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.offset(30);
    }];
    //文字
//    [helpLabel mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(certainBtn.mas_bottom).offset(12);
//        make.centerX.equalTo(self.view.mas_centerX).offset(0);
//        
//    }];
    
    _text2 = text2;
    _vc1 = vc1;
    _vc2 = vc2;
    _certainBtn = certainBtn;
//    _helpLabel = helpLabel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
